﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI.WebControls;
using Medianamik.Core.Bootstrapping;
using Medianamik.Core.Security;
using Medianamik.Core;
using Medianamik.Core.Configuration;
using Medianamik.Core.Logging;

namespace Medianamik.UI.Web
{
    public partial class Login : BaseExternalPage
    {
        protected static readonly MedianamikConfigSection Config = ((MedianamikConfigSection)ConfigurationManager
            .GetSection(ConfigurationSectionName.MEDIANAMIK));

        protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack) Bootstrapper.GetBootstrapper().AuthenticateRequestNeeded();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                MedianamikLogin.DestinationPageUrl = Config.LoginSuccessUrl;

                var connectionButton = MedianamikLogin.FindControl("cmdLogin") as ImageButton;

                if (connectionButton != null)
                    connectionButton.ImageUrl = String.Format("/medianamik/images/Bt_Connecter_{0}.png", UIShortLang);
            }
        }

        protected string ClientLogoPath
        {
            get { return Config.ClientLogoPath; }
        }

        protected void MedianamikLogin_LoggedIn(object sender, EventArgs e)
        {
            LoginService.SetProfileLastActivity(MedianamikLogin.UserName);
        }

        protected void MedianamikLogin_LoginError(object sender, EventArgs e)
        {
            ShowErrorMessage("Login_InvalidCredentials");
        }

        protected void MedianamikLogin_LoggingIn(object sender, LoginCancelEventArgs e)
        {
            string errorMessage;

            if (!LoginService.UserIsValid(MedianamikLogin.UserName, out errorMessage))
            {
                e.Cancel = true;
                ShowErrorMessage(errorMessage);
            }
        }

        private void ShowErrorMessage(string value)
        {
            var lblError = (Label)MedianamikLogin.FindControl("lblError");
            lblError.Visible = true;
            lblError.Text = (string)HttpContext.GetGlobalResourceObject("Medianamik_Global", value);
            var logger = new ActivityLogger();
            logger.Log(new LoggableObject("ConnectionFailure", LogEntryType.Login), value, string.Empty);
        }
    }
}